<template>
  <a-modal v-model:open="isShow" title="新增" @cancel="handleCancel" style="width: 700px">
    <a-spin :spinning="btnLoading">
      <a-form ref="form" :model="formState" :rules="rules" style="margin-top: 30px" :label-col="{ span: 6 }" :wrapper-col="{ span: 14 }">
        <a-form-item label="字典名称" name="dictName">
          <a-input v-model:value="formState.dictName" />
        </a-form-item>
        <a-form-item label="字典编码" name="dictCode">
          <a-input v-model:value="formState.dictCode" type="dictCode" autocomplete="off" />
        </a-form-item>
        <a-form-item  label="描述" name="description">
          <a-input v-model:value="formState.description" type="description" autocomplete="off" />
        </a-form-item>
      </a-form>
    </a-spin>
    <template #footer>
      <a-button @click="handleCancel">取消</a-button>
      <a-button type="primary" :loading="btnLoading" @click="handleOk">确定</a-button>
    </template>
  </a-modal>
</template>
<script setup>
import {computed, reactive, ref} from "vue";
import {message} from "ant-design-vue";
import {addDict} from "@/api/system/dict.js";
import {checkUserName} from "@/api/system/user.js";
const form = ref()
const btnLoading = ref(false)
const emit = defineEmits(['close'])
const props = defineProps({
  openAdd:{
    type: Boolean,
    default: false
  },
})
const formState = reactive({
  dictName: '',
  dictCode: '',
  description: ''
})
const isShow = computed(() => {
  return props.openAdd
})
/**
 * 取消
 */
const handleCancel = () => {
  emit('close')
  form.value.resetFields()
}
/**
 * 确定
 */
const handleOk = async () => {
  try{
    const validate = await form.value.validate()
    try{
      btnLoading.value = true
      const res = await addDict(formState)
      message.success('新增成功')
      emit('close')
      form.value.resetFields()
    }catch (e){
      message.error(e)
    }finally {
      btnLoading.value = false
    }
  }catch (e){}
}

const validateDictCode = async (rule, value) =>{
  console.log(123)
  // 重复校验
  let params = {
    tableName: 'app_dict',
    fieldName: 'dict_code',
    fieldVal: value,
  }
  const res = await checkUserName(params)
    if (res.success) {
      return Promise.resolve()
    } else {
      return Promise.reject(res.message)
    }
}
const rules = {
  dictName: [
    {required: true,trigger: 'change', message: '请输入字典名称!',},
  ],
  dictCode: [
    {required: true, message: '请重新输入字典编码!',},
    {validator: validateDictCode, trigger: 'change'}
  ],
}
</script>
<style scoped>

</style>
